#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXSIZ 4096
#define FIFOLEN 128

void enter(unsigned long in)
{
    int wr_fd, rd_fd;
    char snd_buf[MAXSIZ] = "String from \"enter\" to \"depart\"";
    char rec_buf[MAXSIZ];

    int len = strlen(snd_buf);
    char wr_fifo[FIFOLEN], rd_fifo[FIFOLEN];

    sprintf(wr_fifo, "%lu", (unsigned long)getpid());
    sprintf(rd_fifo, "%lu", in);
    

    int ret = mkfifo(wr_fifo, 0777);
    if (ret != 0) {
        fprintf(stderr, "Counld not create fifo %s/n",wr_fifo);
        exit(EXIT_FAILURE);
    } else {
        printf("FIFO %s creation success!\n",wr_fifo);
    }
    wr_fd = open(wr_fifo, O_WRONLY);
    if (wr_fd != -1) {
        ret = write(wr_fd, snd_buf, len);
        if (ret == -1) {
            fprintf(stderr, "write error on pipe\n");
            exit(EXIT_FAILURE);
        }
    }
    close(wr_fd);


    rd_fd = open(rd_fifo, O_RDONLY);
    if (rd_fd != -1) {
        ret = read(rd_fd, rec_buf, MAXSIZ);
        if (ret == -1) {
            fprintf(stderr, "Write error on pipe\n");
            exit(EXIT_FAILURE);
        }
        printf("Process \"enter\" receives a message from \"depart\": %s", rec_buf);
    }
    close(rd_fd);
}

void depart(unsigned long in)
{
    int wr_fd, rd_fd, ret;
    char snd_buf[MAXSIZ] = "String from \"depart\" to \"enter\"";
    char rec_buf[MAXSIZ];

    int len = strlen(snd_buf);
    char wr_fifo[FIFOLEN], rd_fifo[FIFOLEN];

    sprintf(wr_fifo, "%lu", (unsigned long)getpid());
    sprintf(rd_fifo, "%lu", in);
    

    rd_fd = open(rd_fifo, O_RDONLY);
    if (rd_fd != -1) {
        ret = read(rd_fd, rec_buf, MAXSIZ);
        if (ret == -1) {
            fprintf(stderr, "Write error on pipe\n");
            exit(EXIT_FAILURE);
        }
        printf("Process \"depart\" receives a message from \"enter\": %s", rec_buf);
    }
    close(rd_fd);


    ret = mkfifo(wr_fifo, 0777);
    if (ret != 0) {
        fprintf(stderr, "Counld not create fifo %s/n",wr_fifo);
        exit(EXIT_FAILURE);
    } else {
        printf("FIFO %s creation success!\n",wr_fifo);
    }
    wr_fd = open(wr_fifo, O_WRONLY);
    if (wr_fd != -1) {
        ret = write(wr_fd, snd_buf, len);
        if (ret == -1) {
            fprintf(stderr, "write error on pipe\n");
            exit(EXIT_FAILURE);
        }
    }
    close(wr_fd);
}

int main()
{
    pid_t pid = fork();
    if (pid<0) {
        perror("fork error!\n");
        exit(1);
    } else if (pid==0){
       enter((unsigned long)getppid) ;
    } else {
       depart((unsigned long)pid);
    }
    exit(0);
}
